package com._bytecode.__javassist;

import javassist.*;

import java.io.IOException;

/**
 * @Author: huangya
 * @Date: 2019/3/30
 * @Description:
 */
public class ObjectCreate {

    public static void main(String[] args) throws CannotCompileException, NotFoundException, IOException {
        ClassPool classPool = ClassPool.getDefault();
        //1.创建User类
        CtClass ctClass = classPool.makeClass("com.hy.classloader_demo.__javassist.User1");
        //2.创建name、age属性
        CtField nameField = CtField.make("private String name;", ctClass);
        CtField ageField = CtField.make("private Integer age;", ctClass);
        //3.添加属性
        ctClass.addField(nameField);
        ctClass.addField(ageField);
        //4.创建方法
        CtMethod ctMethod = CtMethod.make("public String getName() {return name;}", ctClass);
        //5.添加方法
        ctClass.addMethod(ctMethod);
        //6.创建构造器
        CtConstructor ctConstructor = new CtConstructor(new CtClass[]{classPool.get("java.lang.String"), classPool.get("java.lang.Integer")}, ctClass);
        ctConstructor.setBody("{this.name = name;this.age = age;}");
        //7.添加构造器
        ctClass.addConstructor(ctConstructor);
        //8.生成class文件
        ctClass.writeFile("D:\\idea_workspace_demos\\classloader_demo\\src\\main\\java");
//        ctClass.writeFile(); //缺省是工程路径
    }

}
